package com.snj.test;

public class GroupRebalance {
    public static void main(String[] args) {
        int constructionDept = 25;
        int serviceDept = 22;

        // 分组处理
        int[] constructionGroups = createGroups(constructionDept, 13);
        int[] serviceGroups = createGroups(serviceDept, 13);

        // 输出原始分组结果
        System.out.println("施工部门分组: " + printGroups(constructionGroups));
        System.out.println("服务部门分组: " + printGroups(serviceGroups));

        // 剩余人数处理
        int remainingConstruction = constructionDept % 13;
        int remainingService = serviceDept % 13;

        // 检查和重新平衡
        serviceGroups = rebalanceGroups(serviceGroups, remainingConstruction);

        // 输出最终分组结果
        System.out.println("最终施工部门分组: " + printGroups(constructionGroups));
        System.out.println("最终服务部门分组: " + printGroups(serviceGroups));
    }

    private static int[] createGroups(int people, int groupSize) {
        int fullGroups = people / groupSize;
        int remainingPeople = people % groupSize;
        int[] groups;
        if (remainingPeople > 0) {
            groups = new int[fullGroups + 1];
        } else {
            groups = new int[fullGroups];
        }
        for (int i = 0; i < fullGroups; i++) {
            groups[i] = groupSize;
        }
        if (remainingPeople > 0) {
            groups[fullGroups] = remainingPeople;
        }
        return groups;
    }

    private static int[] rebalanceGroups(int[] groups, int extraPerson) {
        for (int i = 0; i < groups.length; i++) {
            if (groups[i] < 13) {
                groups[i] += extraPerson; // 将多余的人加到小于13的组
                break;
            }
        }
        return groups;
    }

    private static String printGroups(int[] groups) {
        StringBuilder sb = new StringBuilder();
        for (int group : groups) {
            sb.append(group).append("人一组, ");
        }
        sb.delete(sb.length() - 2, sb.length()); // 删除最后的逗号和空格
        return sb.toString();
    }
}